package com.meta.platform.login.plus.security.provider;

import java.util.Optional;

import com.meta.platform.login.plus.security.LoginSimpleAuthenticationToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

/**
 * 验证码提供者
 * @author pengjianfeng
 * @version 1.0
 * @date 2021/1/12 9:39 上午
 */
@Component
@Slf4j
public class LoginSimpleAuthenticationProvider implements AuthenticationProvider {

    public LoginSimpleAuthenticationProvider(){
        log.info("==============VCodeAuthenticationProvider Instance==================");
    }

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {

        LoginSimpleAuthenticationToken authenticationToken = (LoginSimpleAuthenticationToken) authentication;
        UserDetails user = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());
        Optional.ofNullable(user).orElseThrow(() -> new InternalAuthenticationServiceException("无法获取用户信息"));

        LoginSimpleAuthenticationToken authenticationResult = new LoginSimpleAuthenticationToken(user, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return LoginSimpleAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
